import pymysql
import time
import oss2
path = '/data1/wxp_oss/img9/'


import os
task_id = 250497
company_id = 218705
clue_id = 284927
pic = "http://elephant-spider.oss-cn-beijing.aliyuncs.com/"
db = pymysql.connect("rm-2ze108d8naeso02i1872.mysql.rds.aliyuncs.com", "elephant", "K6hd562P1m", "compare_v2",
                     charset="utf8")
cursor = db.cursor()
def insert(oss_url,pic_url):


	sql = """INSERT INTO compare_218705(task_id,company_id,clue_id, oss_url,width,height,size,img_format,url ,pic_url)
	         VALUES (%s, %s,%s,'%s',%s,%s, %s, %s,'%s','%s') """ % (250497,218705,284927, oss_url,400,400,50,1,"gettyimages",pic_url)

	try:
		# 执行sql语句
		cursor.execute(sql)
		# 提交到数据库执行
		db.commit()
	except:
		# 如果发生错误则回滚
		db.rollback()



def getallfile(path):
	allfile = []
	allfilelist = os.listdir(path)
	for file in allfilelist:
		filepath = os.path.join(path, file)
		allfile.append(filepath)
	return allfile


def getFilename(filename):
	(filepath, tempfilename) = os.path.split(filename)
	(shotname, extension) = os.path.splitext(tempfilename)
	return shotname


def getFileExtension(filename):
	(filepath, tempfilename) = os.path.split(filename)
	(shotname, extension) = os.path.splitext(tempfilename)
	return extension


def gettempfilename(filename):
	(filepath, tempfilename) = os.path.split(filename)
	(shotname, extension) = os.path.splitext(tempfilename)
	return tempfilename


def up_oss(oss_name, image_path ):

	auth = oss2.Auth('LTAIEttoCZFhaQPz', 'R4PmoSfvVTV0DMayktj4vSbwxVz13u')
	bucket = oss2.Bucket(auth, 'vpc100-oss-cn-beijing.aliyuncs.com', 'elephant-spider')
	oss_url = bucket.put_object_from_file(oss_name, image_path)
	print(oss_url)


allimages = getallfile(path)
print(allimages)
for i in allimages:
	task= 250497
	company = 218705
	clue = 284927
	f_name = str(task) + str(company) + str(clue)
	nt = int(time.time()//1)
	frist_name = str(nt)
	# print(frist_name)
	# print(type(frist_name))

	b = gettempfilename(i)
	# print(b)
	oss_name = f_name +frist_name + b
	pic_url = pic + oss_name
	print(pic_url)
	print(oss_name)
	print(i)

	up_oss(oss_name, i)
	insert(oss_name,pic_url)
	os.remove(i)


# 关闭数据库连接
db.close()